

#include<stdio.h>
#include<iostream>
struct treenode {
	treenode* left;
	treenode* right;
	int data;

};

treenode* create() {
	int k;
	scanf("%d", &k);
	if (k == 0) return NULL;
	treenode* root = new treenode;
	root->data = k;
	root->left = create();
	root->right = create();
	return root;
}

typedef struct treenode TN;
void visit(int data){
	printf("%d ",data);
}
void inorder(TN* root) {
	if (root==NULL) return;
	inorder(root->left);
	visit(root->data);
	inorder(root->right);
}

void del(treenode* &root) {
	if (root == NULL) return;
	del(root->left);
	del(root->right);
	delete root;
	root = NULL;
}

bool delt(treenode *&root, treenode* p) {
	if (root == NULL || p == NULL) return false;
	if (p == root) { del(root); return true; }
	if (delt(root->left, p)) return true;
	return delt(root->right, p);
}

treenode* search(treenode* root, int k) {
	if (root == NULL) return NULL;
	if (root->data == k) return root;
	treenode* ans = search(root->left, k);
	if (ans != NULL) return ans;
	return search(root->right, k);
}

int main() {
	int m, k[110];
	treenode*rot=create();
	scanf("%d", &m);
	int p;
	for (p = 0; p < m; p++) {
		scanf("%d", &k[p]);}
	for (p = 0; p < m; p++) {
		struct treenode* v = search(rot, k[p]);
			if (v == NULL) { printf("0\n"); continue; }
			delt(rot,v);
		inorder(rot);
		printf("\n");
		
	}
	return 0;
	}






